package zqkcom.atguigu.filter;

import zqkcom.atguigu.utils.JDBCUtils;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.sql.Connection;
import java.sql.SQLException;

public class TransactionFilter extends HttpFilter {


    @Override
    public void doFilter(HttpServletRequest request, HttpServletResponse response, FilterChain chain) throws IOException, ServletException {

        //获取链接对象
        Connection connection = JDBCUtils.getConnection();
        //取消当前连接的自动提交事务
        try {
            System.out.println("事务过滤开始");
            connection.setAutoCommit(false);
            //执行功能及处理请求
            chain.doFilter(request,response);
            System.out.println("操作成功");
            //执行到此处表示没有异常，需要提交事务
            connection.commit();
        } catch (Exception e) {
            try {
                System.out.println("操作失败");
                //执行到此处表示有异常，需要回滚事务
                connection.rollback();
                //操作失败响应客户端一个错误页面
                response.sendRedirect(request.getContextPath() + "/pages/client/error.jsp");
            } catch (SQLException ex) {
                ex.printStackTrace();
            }
            e.printStackTrace();
        }finally {
            JDBCUtils.closeConnection(connection);
        }
    }

}
